var selectedRow = '';

function formatMood(str){
   return '<div class=\"gallerys\"><img src="'+ basePath + '/images/common/'+ str +'.png" style="width: 50px;height: 50px;" onerror="whenError(this)" class="gallery-pic"></div>';
}

//通用名称
function formatName(value, row, index) {
    if (!value || value == '') {
        return '<p class="infoView" >暂无内容</p>';
    }
    return '<p class="infoView" >'+value+'</p>';
}

$(function (){
    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;formatName
            openRevokeDiaryPage('info');
        },
    };
    regValidate(["#checkDiaryForm"]);
    laydate.render({
        elem: '#diaryDate'
        ,type: 'datetime'
        ,range: true //或 range: '~' 来自定义分割字符
        // ,value: dateFtt("yyyy-MM-dd hh:mm:ss", preDate) + ' - ' + dateFtt("yyyy-MM-dd hh:mm:ss", curDate)
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
    var now = new Date();
    var date = new Date(now.getTime() + 7 * 24 * 3600 * 1000);
    laydate.render({
        elem: '#topTime'
        ,type: 'datetime'
        ,range: true //或 range: '~' 来自定义分割字符
        ,value: dateFtt("yyyy-MM-dd", now) + " 00:00:00"+ ' - ' + dateFtt("yyyy-MM-dd", date) + " 00:00:00"
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
    $("#imgDiv").hide();


    $("input[name=isTop]").click(function(){
        changeDiv();
    });

});

function formatTime(value, row, index){
    if(value){
        return value.substr(0,value.length-3);
    }
        return '';
}

function formatDataStatus(value, row, index) {
    if (!value || value == '') {
        return '';
    }
    return dataStatusMap[value];
}

function formatType(value, row, index){
    if (!value || value == '') {
        return '';
    }
    return YesOrNo[value];
}

function selectMood(value){
    $("#hiddenMood").val(value);
    doRefresh();
}

function changeDiv(){
    var value = $("input[name=isTop]:checked").val();
    if(value == 'Y'){
        $("#topDiv").show();
    }else{
        $("#topDiv").hide();
    }
}

function getParams(params) {
    var value = $("#hiddenMood").val();
    var userId = $("#userId").val();
    var dataStatus = $("#dataStatus").val();
    var exoteric = $("#exoteric").val();
    var isTop = $("#isTop").val();
    var contents = $("#contents").val();
    var diaryStartTimeStr = "";
    var diaryEndTimeStr = "";
    var timeInterval = $("#diaryDate").val();
    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            diaryStartTimeStr = dates[0];
            diaryEndTimeStr = dates[1];
        }
    }
    var pageSize = params.pageSize;
    var pageNo = params.pageNumber;
    return {
        userId : userId,
        dataStatus : dataStatus,
        mood : value,
        exoteric : exoteric,
        contents : contents,
        isTop : isTop,
        diaryStartTimeStr : diaryStartTimeStr,
        diaryEndTimeStr : diaryEndTimeStr,
        pageSize : pageSize,
        pageNo : pageNo
    };
}

function doRefresh() {
    selectedRow = '';
    var value = $("#hiddenMood").val();
    if(value == 'undefined'|| value == undefined){
        value = '';
    }
    var userId = $("#userId").val();
    var dataStatus = $("#dataStatus").val();
    var exoteric = $("#exoteric").val();
    var isTop = $("#isTop").val();
    var contents = $("#contents").val();
    var diaryStartTimeStr;
    var diaryEndTimeStr;
    var timeInterval = $("#diaryDate").val();
    if(value != ''){
        $("#inputDiv").hide();
        $("#imgDiv").show();
        $("#moodImg").attr('src',basePath + 'images/common/'+ value +'.png');
    }
    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            diaryStartTimeStr = dates[0];
            diaryEndTimeStr = dates[1];
        }
    }
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'checkMoodDiary/pageFindDiaryCheckSuccessData?t=' + new Date().getTime(),
        query: {
            userId : userId,
            dataStatus : dataStatus,
            mood : value,
            exoteric : exoteric,
            contents : contents,
            isTop : isTop,
            diaryStartTimeStr : diaryStartTimeStr,
            diaryEndTimeStr : diaryEndTimeStr
        },
    });
}

function doSetTop(){
    if (!selectedRow || selectedRow == '') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if(selectedRow.dataStatus == 'revoke' || selectedRow.dataStatus == 'fail' || selectedRow.exoteric == 'N'){
        toastr.error('当前日记不支持置顶');
        return;
    }
    $("#topSort").val('');
    $('#topTime').val('');
    var value = selectedRow.isTop;
    if(selectedRow.topStarttime && selectedRow.topEndtime){
        $('#topTime').val(selectedRow.topStarttime + " - " + selectedRow.topEndtime);
    }
    $("#topDiv").show();
    $("#hiddenId").val(selectedRow.id);
    $("#hiddenUserId").val(selectedRow.userId);
    $("input[name=isTop]:eq(1)").prop("checked", true);
    if(value == "Y") {
        $("#topSort").val(selectedRow.topSort);
    } else{
        //$("input[name=isTop]:eq(0)").prop("checked",true);
        $("#topSort").val('');
        //$("#topDiv").hide();
    }
    $('#_score').html(selectedRow.score ? selectedRow.score : '');
    $('#setTopDiary').modal(true);
}

function setDiaryTop(){
    if(!$("#checkDiaryForm").valid()) return;//校验不通过
    var data = getFormData("#checkDiaryForm");
    var topSort = $("#topSort").val();
    if(topSort == null || topSort == ''){
        data.topSort = 999;
    }
    var id = $("#hiddenId").val();
    var userId = $("#hiddenUserId").val();
    var isTop = $("input[name=isTop]:checked").val();
    data.id = id;
    data.userId = userId;
    data.topTime='';
    if(isTop == "Y"){
        var topTimeStr = $("#topTime").val();
        if(topTimeStr){
            var dates = topTimeStr.split(' - ');
            if(dates && dates.length >1){
                data.topStarttime = dates[0];
                data.topEndtime = dates[1];
            }
            if(judgementDate(dates[0],dates[1]) <= 0){
                toastr.error('置顶开始时间必须小于置顶结束时间 ');
                return;
            }
        }
    }else{
        data.topStarttime = '';
        data.topEndtime = '';
        data.topSort = '';
    }
    var url = basePath + 'checkMoodDiary/setDiaryTop?t=' + new Date().getTime() ;
    $.ajax({
        type: 'post',
        url: url,
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success : function (data) {
            if(data && data.result){
                $('#setTopDiary').modal("hide");
                doRefresh();
               // window.location.href = basePath + 'checkMoodDiary/moodDiarySuccessPage?t=' + new Date().getTime() + '&' + $('#searchForm').serialize();
            }else{
                toastr.error(data.message);
            }
        }, error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function doReset(){
    $("#userId").val('');
    //****************重置表情****************************
    $("#inputDiv").show();
    $("#imgDiv").hide();
    $("#hiddenMood").val('');
    $("#moodImg").attr('src','');

    $("#dataStatus").val('');
    $("#exoteric").val('');
    $("#contents").val('');
    $("#diaryDate").val('');
    $("#isTop").val('');
}


function openRevokeDiaryPage(type){
    if (!selectedRow || selectedRow == '') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    var postData = {
        id : selectedRow.id,
        userId : selectedRow.userId,
    };
    var url = basePath + 'checkMoodDiary/openMoodDiaryPage?type='+type+'&t=' + new Date().getTime();
    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        data: postData,
        success : function (data) {
            if(data && data.result){
                showCheckDiaryPage(data.content)
            }else if(data&&!data.result){
                toastr.error(data.message);
            }else{
                toastr.error('查询心情日记信息失败');
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function doRevokeDiary(){
    if (!selectedRow || selectedRow == '') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if(selectedRow.dataStatus == 'revoke'){
        toastr.error('已撤销的数据无需再次撤销发布');
        return;
    }
    if(selectedRow.dataStatus == 'fail'){
        toastr.error('未通过的数据无需再次撤销发布');
        return;
    }
    if(selectedRow.exoteric == 'N'){
        toastr.error('非公开的数据无需撤销发布');
        return;
    }
    /*var str = '确定将选中日记撤销发布吗？';
    swalToastr('撤销发布', str, 'warning', revokeDiary, '确定');*/
    $('#revokeReason').val('很抱歉，您的日记涉嫌违规，请重新上传');
    $('#setRevokeReasonPage').modal('show');
    hideLoading();
}

function revokeDiary(){
    var revokeReason = $('#revokeReason').val();
    if (!revokeReason || revokeReason == '') {
        toastr.error('撤销原因不能为空');
        return;
    }
    var postData = {
        id : selectedRow.id,
        userId : selectedRow.userId,
        isTop : selectedRow.isTop,
        revokeReason : revokeReason,
    };
    $.ajax({
        type: 'post',
        url: basePath + 'checkMoodDiary/revokeDiary',
        dataType: 'json',
        data: postData,
        success: function (data) {
            hideLoading();
            if (data.result) {
                $('#setRevokeReasonPage').modal('hide');
                $('#checkDiary').modal('hide');
                doRefresh();
                //window.location.href = basePath + 'checkMoodDiary/moodDiarySuccessPage?t=' + new Date().getTime() + '&' + $('#searchForm').serialize();
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            hideLoading();
            toastr.error(common_system_error);
        }
    });
}


function showCheckDiaryPage(content){
    if (content) {
        $('#lab_userId').html(content.userId);
        $('#lab_mood').html('');
        var picDiv = '<div class=\"gallerys\"><img src="'+ basePath + '/images/common/'+ content.mood +'.png" style="width: 40px;height: 40px;" onerror="whenError(this)" class="gallery-pic"></div>';
        $('#lab_mood').append(picDiv);
        $('#lab_habitName').html(content.habitName);
        $('#lab_contents').html(content.contents);
        var dataStatus = dataStatusMap[content.dataStatus];
        $('#checkResult').html(dataStatus);
        $('#filedReason').html('');
        $('#revoke').hide();
        $('#tips').html('');
        $('#revokeTips').html('');
        if(content.dataStatus == 'pass' && content.exoteric == 'Y'){
            $('#tips').html('审核说明:');
            $('#filedReason').html('审核通过');
            $('#revoke').show();
            $('#revokeTips').html('(撤销发布后，用户已发布日记会从所有人可见变成仅自己可见)');
        }else if(content.dataStatus == 'fail'){
            $('#tips').html('审核说明:');
            $('#filedReason').html(content.reason);
        }else if(content.dataStatus == 'pass'){
            $('#tips').html('审核说明:');
            $('#filedReason').html('审核通过');
        }
        //var defPath = basePath + 'images/main/default.jpg';
        var div = '';
        $("#picDiv").html('');
        var picList = content.picList;
        if(picList && picList.length > 0){
            $.each(picList,function(index,value){
                div += '<img style="float:left;width: 180px;height: 150px" id="coverUrlImg" onclick="$.openPhotoGallery(this)" src="'+ value +'" class="img-rounded win-img gallery-pic">';
            });
        }
        $("#picDiv").append(div);
    }
    $('#checkDiary').modal(true);
}


$("#dataTable").on("click-row.bs.table",function(e,row,ele){
    $("#dataTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedRow = row;
});